<template>
    <h1>用户投资页面</h1>

    <table>
        <tr>
            <td>投资项目名称</td>
            <td>
                {{ Info.I_Name }}
            </td>
        </tr>

        <tr>
            <td>投资总金额</td>
            <td>
                {{ Info.I_Budget }}
            </td>
        </tr>

        <tr>
            <td>已投资金额</td>
            <td>
                {{ Info.I_Receive }}
            </td>
        </tr>

        <tr>
            <td>投资项目剩余额度</td>
            <td>
                {{ Info.I_Residue }}
            </td>
        </tr>

        <tr>
            <td>投资金额</td>
            <td>
                <input type="text" v-model="NMoney" @change="GetMoney" >
            </td>
        </tr>

        <tr>
            <td>预期最高收益</td>
            <td>
                {{ NMaxMoney }}
            </td>
        </tr>

        <tr>
            <td colspan="2">
                <input type="button" value="确认投资" @click="AddUserInvest" >
            </td>
        </tr>

    </table>

</template>

<script setup lang="ts">
import {ref,onMounted} from 'vue';
import axios from 'axios';
import { useRouter,useRoute } from 'vue-router';
import {useUserStore} from '../../store/index'

const useStore = useUserStore();//创建仓库实例

const route = useRoute();//路由操作对象

const router = useRouter();//路由实例对象

console.log(route.params.Id)//投资编号
console.log(useStore.UId)//用户编号

const Info = ref({
    I_Name:'',
    I_Budget:0,
    I_Receive:0,
    I_Residue:0
})

const NMoney = ref('');//用户投资金额
const NMaxMoney = ref(0);

//生命周期钩子
onMounted (()=>{
    SearInvest();
})
//反填方法
const SearInvest = ()=>{
    axios({
        method:'get',
        url:'http://localhost:63517/api/Invest/SearInvest',
        params:{
            Id:route.params.Id
        }
    })
    .then((res)=>{
        console.log(res.data);
        Info.value = res.data;
    })
    .catch((err)=>{
        console.log(err);
    })
}

//计算预期最高收益
const GetMoney = ()=>{
    NMaxMoney.value = Number( NMoney.value )*0.08  ;
}

//添加用户投资信息
const AddUserInvest = ()=>{
    if(NMoney.value==''){
        alert("投资金额不能为空");
        return;
    }

    if(NMoney.value > String(Info.value.I_Residue)  ){
        alert("投资金额不能大于投资项目剩余金额");
        return;
    }

    axios({
        method:'post',
        url:'http://localhost:63517/api/Invest/AddUserInvestData',
        data:{
            UI_Money:NMoney.value,//用户投资金额
            U_Id:useStore.UId,//用户编号
            I_Id:route.params.Id//用户编号
        }
    })
    .then(res=>{
        if(res.data>0){
            alert('用户投资成功');
            router.push('/ShowUserInvestInfo')
        }
        else{
            alert('用户投资失败');
        }
    })
    .catch(err=>{
        console.log(err);
    })
}

</script>
